package cn.com.cfae.iras.doc.analyze.parse.extractor;

import cn.com.cfae.iras.doc.analyze.parse.GsonUtil;
import cn.com.cfae.iras.doc.analyze.parse.kv.KVText;
import cn.com.cfae.iras.doc.analyze.parse.kv.TextLayout;
import cn.com.cfae.iras.doc.analyze.pdf.PdfExtractor;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.soap.Text;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 抽取基类
 */
public abstract class TableExtractor extends BaseExtractor {

    protected void extract() {
    }

    private static Logger logger = LoggerFactory.getLogger(TableExtractor.class);


    protected List<String> commandLine(String[] args) throws Exception {
        CommandLineParser parser = new DefaultParser();
        CommandLine cmd = parser.parse(PdfExtractor.buildOptions(), args);
        return new PdfExtractor(cmd).extractTables(cmd);
    }


    protected List<String> extractPdfByText(String[] args) throws Exception {
        return commandLine(args);

    }

    protected List<String> extractPdfByTable(String[] args) throws Exception {
        List<String> tableDataList = commandLine(args);
        if (tableDataList.size() <= 3) {
            return tableDataList;
        } else {
            return findValidTableData(tableDataList);
        }
    }

    protected List<String> findValidTableData(List<String> tableDataList) {
        int previousColumnSize = 0;
        int previousOffset = -1;
        for (int i = 0; i < tableDataList.size(); i++) {
            String tableData = tableDataList.get(i);
            JsonArray tableDataArray = GsonUtil.getInstance().parse(tableData).getAsJsonArray();
            JsonArray dataArray = tableDataArray.get(0).getAsJsonObject().get("data").getAsJsonArray();
            int columnSize = dataArray.get(0).getAsJsonArray().size();
            if (previousColumnSize > 0) {
                if (columnSize > previousColumnSize) {
                    previousColumnSize = columnSize;
                    previousOffset = i;
                }
            } else {
                previousColumnSize = columnSize;
                previousOffset = i;
            }
        }
        return Arrays.asList(new String[]{tableDataList.get(previousOffset)});
    }

    protected TextLayout findTextArea(JsonElement cell, JsonElement tableData) {
        JsonArray pageDataArray = tableData.getAsJsonArray();
        JsonObject pageData = pageDataArray.get(0).getAsJsonObject();
        JsonArray dataArray = pageData.get("data").getAsJsonArray();
        for (int i = 0; i < dataArray.size(); i++) {
            JsonArray itemArray = dataArray.get(i).getAsJsonArray();
            JsonObject var2 = findValidTableCell(itemArray);
            if (var2 == null) {
                continue;
            }
            if (isInner(cell.getAsJsonObject(), var2)) {
                TextLayout kTextLayout = createKVTextLayout(var2);
                kTextLayout.setText(replaceSpecialChar(cell.getAsJsonObject().get("text").getAsString()));
                return kTextLayout;
            }
        }
        return null;
    }

    /**
     * 获取单元格的X轴
     * @param jsonObject
     * @param tableJsonObject
     * @return
     */
    protected TextLayout createKVTextLayout(JsonObject jsonObject,JsonObject tableJsonObject) {
        double top = jsonObject.get("top").getAsDouble();
        if (top == 0) {
            return null;
        }
        double left = tableJsonObject.get("left").getAsDouble();
        double height = jsonObject.get("height").getAsDouble();
        double width = jsonObject.get("width").getAsDouble();
        return new TextLayout(replaceSpecialChar(jsonObject.get("text").getAsString()), top, left, height, width);
    }

    protected TextLayout createKVTextLayout(JsonObject jsonObject) {
        double top = jsonObject.get("top").getAsDouble();
        if (top == 0) {
            return null;
        }
        double left = jsonObject.get("left").getAsDouble();
        double height = jsonObject.get("height").getAsDouble();
        double width = jsonObject.get("width").getAsDouble();
        return new TextLayout(replaceSpecialChar(jsonObject.get("text").getAsString()), top, left, height, width);
    }

    protected TextLayout findTextArea2(JsonElement cell, JsonElement tableData) {
        JsonArray pageDataArray = tableData.getAsJsonArray();
        JsonObject pageData = pageDataArray.get(0).getAsJsonObject();
        JsonArray dataArray = pageData.get("data").getAsJsonArray();
        TextLayout kTextLayout = null;
        for (int i = 0; i < dataArray.size(); i++) {
            JsonArray itemArray = dataArray.get(i).getAsJsonArray();
            List<JsonObject> jsonObjectList = findValidTableCells(itemArray);
            if (jsonObjectList.isEmpty()) {
                continue;
            }
            for (int j = 0; j < jsonObjectList.size(); j++) {
                JsonObject var2 = jsonObjectList.get(j);
                if (isInner(cell.getAsJsonObject(), var2)) {
                    kTextLayout = createKVTextLayout(var2,cell.getAsJsonObject());
                    kTextLayout.setText(replaceSpecialChar(cell.getAsJsonObject().get("text").getAsString()));
                    break;
                }
            }
            if (kTextLayout != null) {
                break;
            }
        }
        return kTextLayout;
    }

    protected List<JsonObject> findValidTableCells(JsonArray itemArray) {
        List<JsonObject> jsonObjectList = new ArrayList<>();
        for (int i = 0; i < itemArray.size(); i++) {
            JsonObject cell = itemArray.get(i).getAsJsonObject();
            String text = cell.get("text").getAsString();
            if (StringUtils.isNotEmpty(text)) {
                jsonObjectList.add(cell);
            }
        }
        return jsonObjectList;
    }

    protected JsonObject findValidTableCell(JsonArray itemArray) {
        List<JsonObject> jsonObjectList = findValidTableCells(itemArray);
        if (!jsonObjectList.isEmpty()) {
            return jsonObjectList.get(0);
        }
        return null;
    }

    protected boolean isInner(JsonObject var1, JsonObject var2) {
        double var1Width = var1.getAsJsonObject().get("width").getAsDouble();
        double var1Height = var1.getAsJsonObject().get("height").getAsDouble();
        double var1Top = var1.getAsJsonObject().get("top").getAsDouble();
        double var1Left = var1.getAsJsonObject().get("left").getAsDouble();

        double var2Width = var2.getAsJsonObject().get("width").getAsDouble();
        double var2Height = var2.getAsJsonObject().get("height").getAsDouble();
        double var2Top = var2.getAsJsonObject().get("top").getAsDouble();
        double var2Left = var2.getAsJsonObject().get("left").getAsDouble();
//        if ((var1Top < var2Top) && (var1Left < var2Left) && (var1Left + var1Width) > var2Left && (var1Top + var1Height) > (var2Top + var2Height)) {
//            return true;
//        }
        if ((var1Top < var2Top)  && (var1Left + var1Width) > var2Left && (var1Top + var1Height) > (var2Top + var2Height)) {
            return true;
        }
        return false;
    }

    protected String replaceSpecialChar(String text) {
        return text.replaceAll("[,:“”\r]", "");
    }
}
